package com.hltx.controller.order;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hltx.controller.base.BaseController;
import com.hltx.pojo.common.Page;
import com.hltx.pojo.order.Order;
import com.hltx.pojo.pay.OrderInfo;
import com.hltx.pojo.user.User;
import com.hltx.resolver.DefiniteException;
import com.hltx.service.order.OrderManager;
import com.hltx.service.pay.PayManager;
import com.hltx.service.user.UserManager;
import com.hltx.util.DateUtil;
import com.hltx.util.ResultInfo;





/**
 * 订单controller
 */
@Controller
@RequestMapping("/order")
public class OrderController extends BaseController{

	@Resource(name="orderService")
	private OrderManager orderService;
	
	@Autowired
	private PayManager payService;
	
	/*@Autowired
	private ConsumeBrokerageService brokerageService;
	
	@Autowired
	private GoodsManager goodsService;
	*/
	@Resource(name = "userService")
	private UserManager userService;
	/**
	 * 打开订单列表
	 */ 
	@RequestMapping
	public String index(Page page,HttpServletRequest request) {
		if(request.getParameter("type")!=null && request.getParameter("type")!=""){
			boolean bl=StringUtils.isNumeric(request.getParameter("state"));
			if(!request.getParameter("type").equals("stateOrder") || bl==false || 
					request.getParameter("state") == null || request.getParameter("state")==""){
				throw new DefiniteException("参数不正确！");
			}
			request.setAttribute("status", request.getParameter("state"));
		}
		return "order/order_list";
	}
	
	
	@RequestMapping(value = "/getOrderList", method = { RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public Map<String,Object> getGoodsList(Page page, HttpServletRequest request, HttpSession session){
		this.logBefore(logger, "查询订单列表");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
			//获取用户信息
			User user=(User) request.getSession().getAttribute("sessionUser");
			page.getParams().put("userid", user.getId());
			//获取订单列表
			List<Order> orderList=orderService.getOrderList(page);
			
			Map<String,Order> resOrderMap = new TreeMap<String,Order>(Collections.reverseOrder());

			int sum=0;
			for(Order order:orderList){
				Long orderID = order.getOrder_id();
				String state =order.getState()== null?"":order.getState();
				String code=order.getCode()== null?"":order.getCode();
				int goodsID =order.getGoods_id();
				String goodsThumb = order.getGoodsThumb()== null?"":order.getGoodsThumb();
				String title=order.getTitle()== null?"":order.getTitle();
				String subTitle=order.getSubTitle()== null?"":order.getSubTitle();
				String specDesc=order.getSpecDesc()== null?"":order.getSpecDesc();
				int returnPoints=order.getReturnPoints();
				BigDecimal currentPrice=order.getCurrentPrice();
				BigDecimal price=order.getPrice();
				int number=order.getNumber();
				String isPointsBuy=order.getIsPointsBuy();
				int usePointsNum=order.getUsePointsNum();
				BigDecimal usePrice=order.getUsePrice();
				BigDecimal realPrice=order.getRealPrice();
				BigDecimal transitPrice=order.getTransitPrice();
				int cur_pay_points =order.getCur_pay_points();
				BigDecimal cur_pay_price=order.getCur_pay_price();
					Order g = new Order();
					g.setGoodsThumb(goodsThumb);
					g.setGoods_id(goodsID);
					g.setTitle(title);
					g.setSubTitle(subTitle);
					g.setSpecDesc(specDesc);
					g.setCurrentPrice(currentPrice);
					g.setPrice(price);
					g.setNumber(number);
					g.setIsPointsBuy(isPointsBuy);
					g.setUsePrice(usePrice);
					g.setUsePointsNum(usePointsNum);
					g.setReturnPoints(returnPoints);
					
				if(!resOrderMap.containsKey(orderID+"S")){
					Order o = new Order();
					o.setId(orderID);
					//生产唯一订单码
					o.setOrder_id(Long.parseLong(code.substring(0,4)+orderID+code.substring(code.length()-7,code.length())));
					o.setState(state);
					o.setRealPrice(realPrice);
					o.setTransitPrice(transitPrice);
					o.setCur_pay_points(cur_pay_points);
					o.setCur_pay_price(cur_pay_price);
					o.setReturnPoints(returnPoints);
					
					sum=number;
					o.setSum(sum);
					o.getGoodsList().add(g);
					resOrderMap.put(orderID+"S",o);
				}else{
					Order o = resOrderMap.get(orderID+"S");
					sum+=number;
					o.setSum(sum);
					o.setReturnPoints(returnPoints);
					o.getGoodsList().add(g);
				}		
			}
			
			resMap.put("resOrderMap", resOrderMap);
			resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", ""));
		}catch(Exception e){
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		this.logAfter(logger);
		return resMap;
	}
	
	/**
	 * 打开订单详情
	 */
	@RequestMapping("/detail")
	public String detail(HttpServletRequest request) {
		boolean bl=StringUtils.isNumeric(request.getParameter("orderID"));
		if(bl==false ||request.getParameter("orderID").length()<11 || request.getParameter("orderID") == null || request.getParameter("orderID")==""){
			throw new DefiniteException("参数不正确！");
		}
			request.setAttribute("orderID", request.getParameter("orderID"));
		return "order/order_detail";
	}
	
	/**
	 * 订单详情列表
	 * */
	@RequestMapping(value = "/detaiList",method = { RequestMethod.POST})
	@ResponseBody
	public Map<String, Object> detaiList(Page page, HttpServletRequest request, HttpSession session){
		this.logBefore(logger, "查询订单详情");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			String orderid=(String) page.getParams().get("orderid");
			String id=orderid.substring(4, orderid.length()-7);
			String codepre=orderid.substring(0,4);
			String codesuf=orderid.substring(orderid.length()-7);
			page.getParams().put("orderID", id);
			page.getParams().put("codepre", codepre);
			page.getParams().put("codesuf", codesuf);
			List<Order> detailList=orderService.getDetailList(page);
			if(detailList!=null){
				Map<Long,Order> dateilMap = new HashMap<Long,Order>();
				for(Order order:detailList){
					Long orderID = order.getOrder_id();
					String state =order.getState()== null?"":order.getState();
					String code=order.getCode()== null?"":order.getCode();
					String createTime=order.getCreateTime();
					String payTime=order.getPayTime()== null?"":order.getPayTime();
					String deliveryTime=order.getDeliveryTime()== null?"":order.getDeliveryTime();
					String closingTime=order.getClosingTime()== null?"":order.getClosingTime();
					BigDecimal totalPrice=order.getTotalPrice();
					BigDecimal transitPrice=order.getTransitPrice();
					int usePoints=order.getUsePoints();
					String receiverName=order.getReceiverName();
					String receiverPhone=order.getReceiverPhone();
					String receiverAddress=order.getReceiverAddress();
					int goodsID =order.getGoods_id();
					String goodsThumb = order.getGoodsThumb()== null?"":order.getGoodsThumb();
					String title=order.getTitle()== null?"":order.getTitle();
					String subTitle=order.getSubTitle()== null?"":order.getSubTitle();
					String specDesc=order.getSpecDesc()== null?"":order.getSpecDesc();
					BigDecimal currentPrice=order.getCurrentPrice();
					BigDecimal price=order.getPrice();
					BigDecimal realPrice=order.getRealPrice();
					int number=order.getNumber();
					String isPointsBuy=order.getIsPointsBuy();
					int usePointsNum=order.getUsePointsNum();
					BigDecimal usePrice=order.getUsePrice();
					
						Order g = new Order();
						g.setGoodsThumb(goodsThumb);
						g.setGoods_id(goodsID);
						g.setTitle(title);
						g.setSubTitle(subTitle);
						g.setSpecDesc(specDesc);
						g.setCurrentPrice(currentPrice);
						g.setPrice(price);
						g.setNumber(number);
						g.setIsPointsBuy(isPointsBuy);
						g.setUsePrice(usePrice);
						g.setUsePointsNum(usePointsNum);
					if(!dateilMap.containsKey(orderID)){
						Order o = new Order();
						o.setId(orderID);
						//生产唯一订单码
						o.setOrder_id(Long.parseLong(code.substring(0,4)+orderID+code.substring(code.length()-7,code.length())));
						o.setState(state);
						o.setCreateTime(createTime);
						o.setPayTime(payTime);
						o.setDeliveryTime(deliveryTime);
						o.setClosingTime(closingTime);
						o.setTotalPrice(totalPrice);
						o.setRealPrice(realPrice);
						o.setTransitPrice(transitPrice);
						o.setUsePoints(usePoints);
						o.setReceiverName(receiverName);
						o.setReceiverPhone(receiverPhone);
						o.setReceiverAddress(receiverAddress);
						o.setTransitPrice(transitPrice);
						
						o.getGoodsList().add(g);
						dateilMap.put(orderID,o);
					}else{
						Order o = dateilMap.get(orderID);
						o.getGoodsList().add(g);
					}		
					
				}
				resMap.put("dateilMap", dateilMap);
				resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", ""));
			}else{
				resMap.put("dateilMap", null);
				resMap.put("result", this.initResult(ResultInfo.ERROR, "failure", "暂无数据"));
			}
		} catch(Exception e){
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		this.logAfter(logger);
		return resMap;
	}
	
	@RequestMapping(value = "/confirmGoods", method = { RequestMethod.POST})
	@ResponseBody
	public Map<String,Object> confirmGoods(Page page, HttpServletRequest request, HttpSession session){
		this.logBefore(logger, "确认收货");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
			//获取用户信息
			User user=(User) request.getSession().getAttribute("sessionUser");
			page.getParams().put("userid", user.getId());
			if(page.getParams().get("orderID")!=null && page.getParams().get("orderID")!=""){
				String orderid=(String) page.getParams().get("orderID");
				long id=Long.parseLong(orderid.substring(4, orderid.length()-7));
				page.getParams().put("orderID", id);	
				page.getParams().put("closing_time",DateUtil.getTime());
				
				OrderInfo oi = payService.getOrderInfoByOId(id);
				if(oi != null){
				page.getParams().put("version", oi.getVersion());
				int num = orderService.confirmGoods(page);
				if(num == 1){
					resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", "确认成功!"));
					return resMap;
				}
//				Map<String, String> params = new HashMap<String, String>();
//				List<Map<String, Object>> list = goodsService.getGoodsDetail(params);
//					if(num == 1){
//						//计算佣金
//						BigDecimal vipPrice = DataUtil.getBigDecimal(oi.getVipPrice());
//						if(vipPrice.compareTo(BigDecimal.ZERO)>0){
//							User curUser = userService.getUserInfo(user.getLoginId());
//							brokerageService.bonusTask(curUser, vipPrice);
//						}
//						resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", "确认成功!"));
//						return resMap;
//					}
				
				}	
			}
			resMap.put("result", this.initResult(ResultInfo.ERROR, "failure", "确认失败!"));
			
		}catch(Exception e){
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		this.logAfter(logger);
		return resMap;
	}
}
